package com.plus.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: plus-easy
 * @ClassName SM
 * @description: 国密加密算法
 * @author: AI
 * @create: 2023-11-23 14:58
 * @Version 1.0
 **/
public class SMUtil {



    //region SM2  可以替代rsa加密，并且速度更快，安全性更高
    public static String sm2PublicKeyEncrypt(String input, String publicKey) {
        return SmUtil.sm2((String)null, publicKey).encryptBcd(input, KeyType.PublicKey);
    }

    public static String sm2PrivateKeyDecrypt(String encryptStr, String privateKey) {
        return SmUtil.sm2(privateKey, (String)null).decryptStr(encryptStr, KeyType.PrivateKey);
    }

    public static Map<String, Object> SM2GenerateKey() {
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        String privateKey = Base64.encode(pair.getPrivate().getEncoded());
        String publicKey = Base64.encode(pair.getPublic().getEncoded());
        Map<String, Object> result = new HashMap(4);
        result.put("privateKey", privateKey);
        result.put("publicKey", publicKey);
        return result;
    }
    //endregion

    //region SM3 类似md5加密
    public static String sm3Encrypt(String input) {
        return SmUtil.sm3(input);
    }
    //endregion


    //region SM4 加密解密的密码一致，可以替代des等对称加密算法
    public static String sm4Encrypt(String input) {
        return SmUtil.sm4().encryptHex(input);
    }

    public static String sm4Decrypt(String encrypt) {
        return SmUtil.sm4().decryptStr(encrypt, CharsetUtil.CHARSET_UTF_8);
    }

    public static String sm4Encrypt(String input, String key) {
        return SmUtil.sm4(Base64.decode(key)).encryptHex(input);
    }

    public static String sm4Decrypt(String encrypt, String key) {
        return SmUtil.sm4(Base64.decode(key)).decryptStr(encrypt, CharsetUtil.CHARSET_UTF_8);
    }

    public static String sm4generateKey() {
        byte[] key = SecureUtil.generateKey("SM4").getEncoded();
        return Base64.encode(key);
    }
    //endregion

}

